// 创建右键菜单
chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: "startElementSelector",
    title: "开始元素选择",
    contexts: ["all"]
  });

  chrome.contextMenus.create({
    id: "copyElement",
    title: "复制已选元素",
    enabled: false, // 初始为不可用
    contexts: ["all"]
  });
});

function startElementSelector(id) {
  chrome.tabs.sendMessage(id, {
    action: 'startSelection'
  });
  chrome.contextMenus.update("copyElement", {
    enabled: false
  });
}

// 监听右键菜单点击事件
chrome.contextMenus.onClicked.addListener(function (info, tab) {
  // console.log("info", info, tab);
  if (info.menuItemId === "startElementSelector") {
    // console.log("chrome", chrome, chrome.tabs);
    // 发送消息到content script开始选择元素
    startElementSelector(tab.id);
  }else if (info.menuItemId === "copyElement") {
    // 复制已选元素到剪贴板
    chrome.tabs.sendMessage(tab.id, {
      action: 'copyElement'
    });
  }
});

// 快捷键监听
chrome.commands.onCommand.addListener((command) => {
  if (command === "toggle-crawler") {
    chrome.tabs.query({
      active: true,
      currentWindow: true
    }, (tabs) => {
      if (tabs.length > 0) {
        startElementSelector(tabs[0].id);
      }
    });
  }
});

// 监听消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'elementSelected') {
    chrome.contextMenus.update("copyElement", {
      enabled: true
    });
  }
});